package main

import (
	"encoding/hex"
	"fmt"
	"strings"

	"github.com/insomniacslk/dhcp/dhcpv4"
)

// parseCommandLineDHCP4Opt82
func parseCommandLineDHCP4Opt82(s string) dhcpv4.Option {
	s = strings.TrimSpace(s)
	if s == "" {
		return dhcpv4.Option{}
	}

	op82SubOpts := make([]dhcpv4.Option, 0, 5)
	for _, sub := range strings.Fields(s) {
		keyVal := strings.SplitN(sub, "#", 2)
		if len(keyVal) != 2 {
			continue
		}
		optKey := keyVal[0]
		optValue, err := hex.DecodeString(keyVal[1])
		if err != nil {
			panic(fmt.Errorf("%q is not a vaild hex representation of string\n", keyVal[1]))
		}

		switch {
		case strings.EqualFold(optKey, "AgentCircuitID") || optKey == "1":
			op82SubOpts = append(op82SubOpts, dhcpv4.Option{Code: dhcpv4.AgentCircuitIDSubOption, Value: &optionValue{optValue}})
		case strings.EqualFold(keyVal[0], "AgentRemoteID") || optKey == "2":
			op82SubOpts = append(op82SubOpts, dhcpv4.Option{Code: dhcpv4.AgentRemoteIDSubOption, Value: &optionValue{optValue}})
		default:
			continue
		}
	}

	return dhcpv4.OptRelayAgentInfo(op82SubOpts...)
}

type optionValue struct {
	data []byte
}

func (o *optionValue) ToBytes() []byte {
	return o.data
}
func (o *optionValue) String() string {
	return fmt.Sprintf("%#v", o.data)
}
